package com.th.admin.controller.adviser;

import cn.hutool.db.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.th.common.constant.HttpStatus;
import com.th.common.core.controller.BaseController;
import com.th.common.core.domain.AjaxResult;
import com.th.common.exception.base.BaseServiceException;
import com.th.common.page.CommonPageResponse;
import com.th.system.domain.UsOrder;
import com.th.system.domain.UsOrderRequire;
import com.th.system.domain.UsTask;
import com.th.system.domain.UsTaskRequire;
import com.th.system.domain.vo.OrderAndRequireVO;
import com.th.system.domain.vo.UsTaskVo;
import com.th.system.service.UsOrderRequireService;
import com.th.system.service.UsOrderService;
import com.th.system.service.UsTaskRequireService;
import com.th.system.service.UsTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.websocket.server.PathParam;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * @author ValcanoZz
 * @creat 2023-06-23-9:18
 */

@Slf4j
@RestController
@RequestMapping("/api/adviser")
@Api(tags = "顾问管理接口")
public class AdviserTaskController extends BaseController {

    @Autowired
    private UsTaskService usTaskService;

    @Autowired
    private UsTaskRequireService usTaskRequireService;

    @Resource
    private UsOrderService usOrderService;

    @Resource
    private UsOrderRequireService usOrderRequireService;

    @ApiOperation("审批订单是否通过: 根据订单id修改订单状态")
    @PutMapping("/order/status/{id}/{status}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult ModifyOrderStatus(@PathVariable("id") Long id, @PathVariable("status") int status) {
        LambdaUpdateWrapper<UsOrder> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UsOrder::getId, id);
        wrapper.set(UsOrder::getStatus, status);
        boolean isSuccess = usOrderService.update(wrapper);
        if (isSuccess) {
            return AjaxResult.success("更新订单状态成功");
        } else {
            return AjaxResult.error(HttpStatus.ERROR, "状态更新失败");
        }
    }

    @ApiOperation("根据订单id查询订单信息")
    @GetMapping("/order/{id}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult getById(@PathVariable("id") Long id) {

        //TODO: 加订单需求

        UsOrder usOrder = usOrderService.getById(id);

        if (usOrder != null) {
            LambdaQueryWrapper<UsOrderRequire> usOrderRequireLambdaQueryWrapper = new LambdaQueryWrapper<>();
            usOrderRequireLambdaQueryWrapper.eq(UsOrderRequire::getOrderId, usOrder.getId());
            UsOrderRequire usOrderRequire = usOrderRequireService.getOne(usOrderRequireLambdaQueryWrapper);
            if (Objects.isNull(usOrderRequire)) {
                throw new BaseServiceException(HttpStatus.ERROR, "error");
            }

            OrderAndRequireVO orderAndRequireVO = new OrderAndRequireVO();
            orderAndRequireVO.setOrder(usOrder);
            orderAndRequireVO.setOrderRequire(usOrderRequire);

            return AjaxResult.success(orderAndRequireVO);
        } else {
            return AjaxResult.error(HttpStatus.ERROR, "查询不到要操作的信息");
        }
    }

    @ApiOperation("分页查询企业订单信息")
    @GetMapping("/{page}/{pageSize}")
    public AjaxResult Page(@PathVariable("page") int page
            , @PathVariable("pageSize") int pageSize
            , @RequestParam(required = false, value = "startingTime") String startingTimeStr
            , @RequestParam(required = false, value = "endingTime") String endingTimeStr
            , @RequestParam(required = false) String title) {

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        LocalDateTime startingTime = null;
        LocalDateTime endingTime = null;
        if (Objects.nonNull(startingTimeStr)) {
            startingTime = LocalDateTime.parse(startingTimeStr, formatter);
        }
        if (Objects.nonNull(endingTimeStr)) {
            endingTime = LocalDateTime.parse(endingTimeStr, formatter);
        }

        //分页构造器
        Page<UsOrder> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<UsOrder> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(Objects.nonNull(title), UsOrder::getTitle, title)
                .ge(Objects.nonNull(startingTimeStr), UsOrder::getUpdateTime, startingTime)
                .lt(Objects.nonNull(endingTimeStr), UsOrder::getUpdateTime, endingTime);

        usOrderService.page(pageInfo, queryWrapper);

        CommonPageResponse<UsOrder> result = new CommonPageResponse<>();
        result.setTotal(pageInfo.getTotal());
        result.setData(pageInfo.getRecords());

        return AjaxResult.success(result);
    }

    @PostMapping("/submit")
    @ApiOperation("顾问提交任务信息")
    public boolean submitTask(@RequestBody UsTaskVo usTaskVo) {
        UsTask usTask = usTaskVo.getUsTask();
        List<UsTaskRequire> requires = usTaskVo.getRequires();
        Long taskId = usTaskService.insertUsTask(usTask);
        for (UsTaskRequire require : requires) {
            require.setTaskId(taskId);
        }
        return usTaskRequireService.insertRequires(requires);
    }

    @GetMapping("/getTaskOne")
    @ApiOperation("查看某个订单所属的任务信息")
    public List<UsTaskVo> getTaskOne(Long orderId) {
        List<UsTask> usTasks = usTaskService.selectTasksByOrderId(orderId);
        return getVoByTasks(usTasks);
    }


    @GetMapping("/getPage")
    @ApiOperation("查看所有任务信息")
    public List<UsTaskVo> getPage(int startPage, int size) {
        List<UsTask> usTasks = usTaskService.selectPage(startPage, size, null);
        return getVoByTasks(usTasks);
    }

    @GetMapping("/getPageByConditions")
    @ApiOperation("分页查询: 可以根据任务的状态，接收的设计师查询，根据需求的年龄区间，男女装，衣服类型，最大成本，设计师等级查询")
    public List<UsTaskVo> selectByConditions(
            Integer startPage, Integer size,
            Integer status, Integer designerId,
            Integer minAge, Integer maxAge, Integer gender, Integer type, Integer cost, Integer level
    ) {
        List<UsTaskVo> list = new ArrayList<>();

        LambdaQueryWrapper<UsTask> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.eq(status != null, UsTask::getStatus, status);
        taskWrapper.eq(designerId != null, UsTask::getDesignerId, designerId);
        List<UsTask> tasks = usTaskService.selectPage(startPage, size, taskWrapper);    // 查到符合条件的任务

        // 在查符合条件的需求，并且这些需求是属于符合条件的任务的

        for (UsTask task : tasks) {
            LambdaQueryWrapper<UsTaskRequire> requireWrapper = new LambdaQueryWrapper<>();
            requireWrapper.ge(minAge != null, UsTaskRequire::getMinAge, minAge);
            requireWrapper.le(maxAge != null, UsTaskRequire::getMinAge, minAge);
            requireWrapper.eq(gender != null && (gender == 1 || gender == 0), UsTaskRequire::getGender, gender);
            requireWrapper.eq(type != null && type >= 0 && type <= 5, UsTaskRequire::getTypes, type);
            requireWrapper.le(cost != null, UsTaskRequire::getCost, cost);
            requireWrapper.ge(level != null, UsTaskRequire::getLevel, level);
            requireWrapper.eq(task.getId() != null, UsTaskRequire::getTaskId, task.getId());
            UsTaskVo vo = new UsTaskVo();
            vo.setUsTask(task);
            vo.setRequires(usTaskRequireService.selectRequiresByTask(requireWrapper));
            list.add(vo);
        }
        return list;
    }

    private List<UsTaskVo> getVoByTasks(List<UsTask> usTasks) {
        List<UsTaskVo> list = new ArrayList<>();
        for (UsTask task : usTasks) {
            List<UsTaskRequire> requires = usTaskRequireService.selectRequiresByTask(task.getId());
            UsTaskVo usTaskVo = new UsTaskVo();
            usTaskVo.setUsTask(task);
            usTaskVo.setRequires(requires);
            list.add(usTaskVo);
        }
        return list;
    }

    @PutMapping("/updateTask")
    public Boolean updateTask(@RequestBody UsTaskVo usTaskVo) {
        UsTask usTask = usTaskVo.getUsTask();
        List<UsTaskRequire> requires = usTaskVo.getRequires();
        usTaskService.updateTask(usTask);
        usTaskRequireService.updateRequires(requires);
        return true;
    }

    @PutMapping("/updateRequire")
    public Boolean updateTask(@RequestBody UsTaskRequire usTaskRequire) {
        usTaskRequireService.updateOne(usTaskRequire);
        return true;
    }

    @DeleteMapping("/deleteTask")
    public Boolean deleteTask(Long taskId) {
        usTaskService.deleteTask(taskId);
        usTaskRequireService.deleteRequireByTaskId(taskId);
        return true;
    }

    @DeleteMapping("/deleteRequire")
    public Boolean deleteRequire(Long requireId) {
        usTaskRequireService.deleteRequire(requireId);
        return true;
    }


}
